<template>
<div id="AddJuese" class="page-blank">
  <van-nav-bar :title="`${ modify ? '修改角色' : '添加角色' }`" left-arrow @click-left="goBack()"/>
  <div class="flex-body">    
    <van-cell-group>  
      <van-field readonly v-if="form.userId" v-model="form.pid" label="上级id"/>
      <van-field readonly v-if="form.userId" v-model="form.userId" label="用户id"/>

      <van-field readonly clickable label="角色" :value="form.roleType" required placeholder="请选择角色" @click="showPickerClick('roleType')"/>
      <van-field v-model="form.nick" required label="用户名称" placeholder="请输入用户名称"/>
      <van-field v-model="form.userName" required label="用户账号" placeholder="请输入用户账号"/>
      <van-field v-model="form.userPhone" required label="绑定手机" placeholder="请输入绑定手机" v-if="!modify || roleType == 0"/>
      <van-field v-model="sms" center clearable required label="短信验证码" placeholder="请输入短信验证码" v-if="!modify">
        <van-button slot="button" size="small" type="primary" @click="sendSms" :loading="smsLoading">{{smsString}}</van-button>
      </van-field>
      <van-field v-model="form.password" v-if="!modify || roleType == 0" type="password" required label="登录密码" placeholder="请输入登录密码"/>
      <template v-if="form.roleType !== '业务员' && form.roleType !== '渠道商'">
        <van-field readonly clickable :value="form.joinWay" required label="加盟方式" placeholder="请选择加盟方式" @click="showPickerClick('joinWay')"/>
        <van-field readonly clickable :value="form.proportionWay" required label="分成方式" placeholder="请选择分成方式" @click="showPickerClick('proportionWay')" v-if="roleType === 0 || shareType === 0"/>
        <van-field readonly clickable v-model="form.divideType" required label="分成基础" placeholder="请选择分成方式" @click="showPickerClick('divideType')" v-if="form.roleType == '商户'"/>
        <van-field v-model="form.virtualProportion" required label="提成比例" placeholder="请输入提成比例"/>
        <van-field v-model="form.dailyEquipmentCost" required label="日常设备成本" placeholder="请输入日常设备成本" v-if="form.proportionWay==='非比例分成'"/>
        <van-field v-model="form.realProportion" label="设备摊销" placeholder="请输入设备摊销" v-if="(roleType === 0 || shareType === 0)&&form.divideType == '绝对分成'&&form.roleType == '商户'"/>
      </template>
      <van-field v-if="form.roleType === '渠道商'" v-model="form.virtualProportion" required label="提成比例" placeholder="请输入提成比例"/>
      <van-field readonly clickable label="状态" :value="form.status" required placeholder="请选择状态" @click="showPickerClick('status')"/>
      <van-field readonly clickable label="弹出宝权限" :value="form.popupPower" required placeholder="请选择弹出宝权限" @click="showPickerClick('popupPower')" v-if="roleType === 0 && form.roleType === '代理'"/>     
      <van-field readonly clickable label="借宝权限" :value="form.lend" required placeholder="请选择借宝权限" @click="showPickerClick('lend')" v-if="roleType === 0 && form.roleType === '代理'"/>     
      <van-field readonly clickable label="买宝钱获取权" :value="form.delayingPurchases" required placeholder="请选择买宝钱获取权" @click="showPickerClick('delayingPurchases')" v-if="roleType === 0 && form.roleType === '代理'"/>
      <van-field label="买宝分成" v-model="form.chargerMoney" placeholder="请输入买宝钱金额" v-if="roleType === 0 && form.roleType === '代理' && form.delayingPurchases == '是'"/>
      <van-field readonly clickable label="分成权限" :value="form.shareType" required placeholder="请选择分成权限" @click="showPickerClick('shareType')" v-if="roleType === 0 && form.roleType != '渠道商'"/>
      <van-field readonly clickable label="提现权限" :value="form.withdraw" required placeholder="请选择提现权限" @click="showPickerClick('withdraw')" v-if="roleType === 0"/>
      <van-button round type="info" size="small" :loading="submitLoading" @click="submit">提交</van-button>
    </van-cell-group>
  </div>

  <van-popup v-model="showPicker" position="bottom">
    <van-picker show-toolbar :columns="columns" @cancel="showPicker = false" @confirm="onConfirm"/>
  </van-popup>
</div>
</template>

<script lang="ts">
import { Vue, Component, Prop } from 'vue-property-decorator';
import axios from '@/utils/request';
const trueOrFalse = [
  { value: 0, text: '是' },
  { value: 1, text: '否' }
]

@Component
export default class AddJuese extends Vue {
  modify: any = false

  form: any = {
    chargerMoney: '',

    pid: '',
    handlersRoleType: '',
    handlerUserId: '',

    roleType: '',
    userName: '',
    joinWay: '购买',
    realProportion: '',
    proportionWay: '比例分成',
    dailyEquipmentCost: '',
    status: '正常',
    divideType: '绝对分成',
    virtualProportion: 0,
    userPhone: '',
    password: '',
    nick: '',
    shareType: '否',
    withdraw: '是',
    popupPower: '否',
    lend: '否',
    delayingPurchases: '否'
  }
  shareType: any = ''
  roleType: any = this.$store.state.userInfo.roleType
  smsString: any = '发送验证码'
  smsFlag: any = true
  sms: any = ''
  smsInt: any = null
  smsLoading: any = false
  picker: any = {
    name: '',
    proportionWayColumns: [
      { value: 0, text: '比例分成' },
      { value: 1, text: '非比例分成' }
    ],
    roleTypeColumns: [
      { value: 1, text: '代理' },
      { value: 2, text: '业务员' },
      { value: 3, text: '商户' },
      { value: 4, text: '渠道商' }
    ],
    joinWayColumns: [
      { value: 0, text: '购买' },
      { value: 1, text: '投放' }
    ],
    statusColumns: [
      { value: 0, text: '正常' },
      { value: 1, text: '禁用' }
    ],
    divideTypeColumns: [
      { value: 1, text: '绝对分成' },
      { value: 2, text: '相对分成' }
    ],
    popupPowerColumns: trueOrFalse,
    lendColumns: trueOrFalse,
    shareTypeColumns: trueOrFalse,
    withdrawColumns: trueOrFalse,
    delayingPurchasesColumns: trueOrFalse
  }
  columns: any = []
  showPicker: any = false
  submitLoading: any = false
  list: any = []
  
  modifyRefresh(v: any) {
    let obj = JSON.parse(JSON.stringify(v));
    obj.roleType = this.picker.roleTypeColumns.find((v: any) => v.value === obj.roleType).text;
    obj.joinWay = this.picker.joinWayColumns.find((v: any) => v.value === obj.joinWay).text;
    obj.status = this.picker.statusColumns.find((v: any) => v.value === obj.status).text;
    if (!obj.divideType) obj.divideType = 1;
    if (obj.divideType == 2) obj.realProportion = obj.virtualProportion;
    obj.divideType = this.picker.divideTypeColumns.find((v: any) => v.value === obj.divideType).text;
    let proportionWay = this.picker.proportionWayColumns.find((v: any) => v.value === obj.proportionWay);
    obj.proportionWay = proportionWay ? proportionWay.text : '';
    let shareType = this.picker.shareTypeColumns.find((v: any) => v.value === obj.shareType);
    obj.shareType = shareType ? shareType.text : '否';    
    let withdraw = this.picker.withdrawColumns.find((v: any) => v.value === obj.withdraw);
    obj.withdraw = withdraw ? withdraw.text : '否';    
    let popupPower = this.picker.popupPowerColumns.find((v: any) => v.value === obj.popupPower);
    obj.popupPower = popupPower?popupPower.text:'否';
    let lend = this.picker.lendColumns.find((v: any) => v.value === obj.lend);
    obj.lend = lend?lend.text:'否';
    obj.delayingPurchases = obj.delayingPurchases == 0 ? '否' : '是';
    obj.userPhone = obj.phone;
    delete obj.phone;
    this.form = obj;
    this.modify = true;
    setTimeout(() => {
      this.form.dailyEquipmentCost = v.dailyEquipmentCost || '';
      console.log(this.roleType);
      console.log(this.shareType);
      console.log(this.form.divideType);
      console.log(this.form.roleType);
    }, 100)
  }
  showPickerClick(name: any) {
    this.picker.name = name;
    this.columns = this.picker[name + 'Columns']
    this.showPicker = true;
  }
  onConfirm(value: any) {
    this.form[ this.picker.name ] = value.text;
    this.showPicker = false;
  }
  sendSms() {
    if(!this.smsFlag) return;
    if(!this.form.userPhone) return this.$toast('请输入绑定手机');
    if(!/^1[3456789]\d{9}$/.test(this.form.userPhone)) return this.$toast('请输入正确的手机号码');
    this.smsLoading = true;
    axios.get('/api/SmsController/sendverifyCode', { phoneNumber: this.form.userPhone }).then((res: any) => {      
      this.smsLoading = false;
      this.$toast('短信验证码发送成功！')
      this.smsFlag = false;
      this.smsString = 60;
      this.smsInt = setInterval(() => {
        this.smsString--
        if(this.smsString==0) {
          this.smsString = '发送验证码';
          this.smsFlag = true;
          clearInterval(this.smsInt)
        }
      }, 1000);
    }).catch((err: any) => {
      this.smsLoading = false;
    })
  }
  submit() {
    if( this.submitLoading ) return ;
    let obj: any = JSON.parse(JSON.stringify(this.form));
    if(obj.roleType === '') return this.$toast('请选择角色');
    if(obj.nick === '') return this.$toast('请输入用户名称');
    if(!/^([a-zA-Z0-9\u4e00-\u9fa5]){1,20}$/.test(obj.nick)) return this.$toast('用户名称只能输入1-20位英文数字汉字');
    if(obj.userName === '') return this.$toast('请输入用户账号');
    if(!/^([a-zA-Z0-9\u4e00-\u9fa5]){1,20}$/.test(obj.userName)) return this.$toast('用户账号只能输入1-20位英文数字汉字');
    if(obj.userPhone === '') return this.$toast('请输入绑定手机');
    if(obj.password === '') return this.$toast('请输入登录密码');
    if(obj.roleType !== '业务员') {
      if(obj.joinWay === '') return this.$toast('请选择加盟方式');
      if(obj.proportionWay === '') return this.$toast('请选择分成方式');
      if(obj.virtualProportion === '') return this.$toast('请输入提成比例');
      if(!/^([1-9]?\d|100)$/.test(obj.virtualProportion)) return this.$toast('提成比例只能为0-100之间的整数');
      if(obj.proportionWay==='非比例分成'&&obj.dailyEquipmentCost === '') return this.$toast('请输入日常设备成本');
      if(obj.dailyEquipmentCost!==''&&!/^[1-5]$/.test(obj.dailyEquipmentCost)) return this.$toast('日常设备成本只能为1-5之间的整数');
      if(obj.realProportion!==''&&!/^([1-9]?\d|100)$/.test(obj.realProportion)) return this.$toast('设备摊销只能为0-100之间的整数');
    } else {
      obj.virtualProportion = 0;
    }
    if(obj.status === '') return this.$toast('请选择状态');
    if(this.sms === ''&&(!this.modify)) return this.$toast('请输入验证码');
    this.submitLoading = true;
    if (obj.chargerMoney) {
      if (isNaN(obj.chargerMoney)) {
        this.$toast('买宝分成需要输入数字');
        return ;
      } else if (obj.chargerMoney > 99 || obj.chargerMoney < 0) {
        this.$toast('买宝分成需要大于0，小于99');
        return ;
      }
    }
    // console.log(obj, obj.chargerMoney);
    // return ;
    if(!this.modify) {
      axios.get('/api/SmsController/checkSmsCode', { 
        phoneNumber: obj.userPhone, code: this.sms 
      }).then((res: any) => {
        this.submitFun();
      }).catch(() => {
        this.submitLoading = false;
      });
    } else {
      this.submitFun();
    }
  }
  submitFun() {
    let obj = JSON.parse(JSON.stringify( this.form ));
    obj.roleType = this.picker.roleTypeColumns.find((v: any) => v.text === obj.roleType).value;
    obj.joinWay = this.picker.joinWayColumns.find((v: any) => v.text === obj.joinWay).value;
    obj.proportionWay = this.picker.proportionWayColumns.find((v: any) => v.text === obj.proportionWay).value;
    obj.shareType = this.picker.shareTypeColumns.find((v: any) => v.text === obj.shareType).value;
    obj.withdraw = this.picker.withdrawColumns.find((v: any) => v.text === obj.withdraw).value;
    obj.divideType = this.picker.divideTypeColumns.find((v: any) => v.text === obj.divideType).value;
    obj.delayingPurchases = obj.delayingPurchases == '否' ? 0 : 1;
    obj.status = this.picker.statusColumns.find((v: any) => v.text === obj.status).value;
    obj.popupPower = this.picker.popupPowerColumns.find((v: any) => v.text === obj.popupPower).value;
    obj.lend = this.picker.lendColumns.find((v: any) => v.text === obj.lend).value;
    if ( !( this.roleType === 0 || this.shareType === 0 ) ) obj.realProportion = obj.virtualProportion;
    if ( obj.roleType == 4 || obj.roleType == 1 ) obj.realProportion = obj.virtualProportion;
    if ( obj.divideType == 2 ) obj.realProportion = obj.virtualProportion;
    obj.phone = obj.userPhone;

    // 所有对象必传值
    obj.handlerUserId = this.$store.state.userInfo.userId;
    obj.handlersRoleType = this.$store.state.userInfo.roleType;

    // obj.password = '123456';

    axios.post('/api/roleController/addRoleModel', obj).then((res: any) => {
      this.$toast(`${ this.modify ? '修改' : '新增' }成功！`);
      this.submitLoading = false;
      this.$router.go( -1 );
    }).catch(() => {
      this.submitLoading = false;
    })
  }


  goBack() {
    this.$router.go(-1);
  }

  mounted() {
    // 必填项 pid
    this.form.pid = this.$store.state.userInfo.userId;

    let roleType = this.$store.state.userInfo.roleType;
    let userRole = this.$store.state.userInfo.role;
    this.shareType = userRole ? userRole.shareType : '';

    if ( roleType == 0 ) {}
    else if ( roleType == 1 ) { 
      // this.picker.roleTypeColumns = this.picker.roleTypeColumns.filter((v: any) => v.value > roleType); 
    } else { this.picker.roleTypeColumns = this.picker.roleTypeColumns.filter((v: any) => v.value > roleType && v.value != 4); }

    if(this.$route.query && this.$route.query.type) {
      if(this.$route.params && this.$route.params.userId) this.modifyRefresh( this.$route.params );
      else this.goBack();
    }
  }
  
};
</script>

